//
//  Noise.m
//  pipi
//
//  Created by zhao ys on 5/14/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SoundManager.h"
#import <AVFoundation/AVFoundation.h>

static SoundManager * _sharedManager = nil;
@implementation SoundManager
+(SoundManager*) sharedManager {
	if (_sharedManager == nil) {
		_sharedManager = [[SoundManager alloc] init];
	}
	return _sharedManager;
}

-(id) init {
	if ((self = [super init])) {
		_players = [[NSMutableDictionary alloc] init];
	}
	return self;
}


-(BOOL) loadSound:(NSString *)file withName:(NSString*)indent {
	NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: file
															  ofType: @""];
	NSLog(@"%@", soundFilePath);
	
	NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
	AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
																	  error: nil];
	
	[newPlayer autorelease];
	
	[fileURL release];
	[newPlayer prepareToPlay];
	[newPlayer setDelegate: self];
	[_players setObject:newPlayer forKey:indent];
	return YES;
}

-(BOOL) unloadSound:(NSString*)indent {
	AVAudioPlayer * player = [_players objectForKey:indent];
	if (player == nil) {
		return NO;
	}
	
	[_players removeObjectForKey:indent];
	[player release];
	return YES;
}

-(BOOL) play:(NSString*)indent loops:(int)loops {
	AVAudioPlayer * player = [_players objectForKey:indent];
	if (player == nil) {
		return NO;
	}
	
	[player play];
	return YES;
}

-(BOOL) stop:(NSString*)indent {
	AVAudioPlayer * player = [_players objectForKey:indent];
	if (player == nil) {
		return NO;
	}
	
	[player stop];
	return YES;
}

- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player
                        successfully: (BOOL) completed {
    if (completed == YES) {
    }
}

-(void)dealloc {
	[_players release];
	[super dealloc];
}

@end
